//
//  YBCommentToolBar.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/21.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBCommentToolBar.h"

//#import "SelPeopleV.h"
#import "XHVoiceRecordHUD.h"
#import "XHVoiceRecordHelper.h"
#import <AFNetworking/AFNetworking.h>

#import "YBStorageObj.h"

@interface YBCommentToolBar()<HPGrowingTextViewDelegate,twEmojiViewDelegate> {
    UIView *_superView;
    int _vcType;
//    SelPeopleV * _selV;
//    twEmojiView *_emojiV;
//    NSMutableArray *_atArray;       //@用户的uid和uname数组
    
    NSString *qntoken;              //七牛token
    
    NSString *tengxunID;
    NSString *bucketName;
    NSString *regionName;
    
    NSString *voicePathhh;
//    NSString *_voiceDution;
    ZFPlayerPlaybackState _playState;
}
//@property(nonatomic,strong)HPGrowingTextView *textField;
@property(nonatomic,strong)UIButton *atBtn;
//@property(nonatomic,strong)UIButton *faceBtn;
//@property(nonatomic,strong)UIButton *voiceBtn;
//@property(nonatomic,strong)UIButton *voiceRecodeBtn;

@property(nonatomic, strong, readwrite) XHVoiceRecordHUD *voiceRecordHUD;
/**
 *  管理录音工具对象
 */
@property(nonatomic, strong) XHVoiceRecordHelper *voiceRecordHelper;
@property(nonatomic,strong)NSDictionary *TXSignDic;

@end

@implementation YBCommentToolBar

- (instancetype)initWithFrame:(CGRect)frame andVCType:(int)vcType superView:(UIView *)superView{
    self = [super initWithFrame:frame];
    if (self) {
        _vcType = vcType;
        _superView = superView;
        _atArray = [NSMutableArray array];
        
        [self createUI];
    }
    return self;
}

-(void)createUI {
    //设置输入框
    UIView *vc  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    vc.backgroundColor = [UIColor clearColor];
    _textField = [[HPGrowingTextView alloc]initWithFrame:CGRectMake(44,8, _window_width - 68-44*2, 34)];
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 17;
    _textField.font = SYS_Font(16);
    _textField.placeholder = YZMsg(@"说点什么吧~");
    _textField.textColor = UIColor.blackColor;
    _textField.placeholderColor = UIColor.grayColor;
    _textField.delegate = self;
    _textField.returnKeyType = UIReturnKeySend;
    _textField.enablesReturnKeyAutomatically = YES;
    
    _textField.internalTextView.textContainer.lineBreakMode = NSLineBreakByTruncatingHead;
    _textField.internalTextView.textContainer.maximumNumberOfLines = 1;
    
    /**
     * 由于 _textField 设置了contentInset 后有色差，在_textField后添
     * 加一个背景view并把_textField设置clearColor
     */
    _textField.contentInset = UIEdgeInsetsMake(2, 10, 2, 10);
    _textField.backgroundColor = [UIColor clearColor];
    _tv_bg = [[UIView alloc]initWithFrame:_textField.frame];
    _tv_bg.backgroundColor = RGB_COLOR(@"#2C2840", 0.2);//RGB(245, 245, 245);//
    _tv_bg.layer.masksToBounds = YES;
    _tv_bg.layer.cornerRadius = _textField.layer.cornerRadius;
    [self addSubview:_tv_bg];
    [self addSubview:_textField];
    
    //@功能
    _atBtn = [UIButton buttonWithType:0];
    _atBtn.backgroundColor = [UIColor clearColor];
    _atBtn.frame = CGRectMake(_window_width - 44-10-34,8,34,34);
    [_atBtn setImage:[UIImage imageNamed:@"@符"] forState:0];
    [_atBtn addTarget:self action:@selector(atFrends) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_atBtn];
    
    //表情
    _faceBtn = [UIButton buttonWithType:0];
    _faceBtn.frame = CGRectMake(_window_width - 44,8,34,34);
    [_faceBtn setImage:[UIImage imageNamed:@"tool_chat"] forState:0];
    [_faceBtn setImage:[UIImage imageNamed:@"chat_keyboard"] forState:UIControlStateSelected];
    [_faceBtn addTarget:self action:@selector(clickFaceBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_faceBtn];
    _faceBtn.selected = NO;
    
    //@声音
    _voiceBtn = [UIButton buttonWithType:0];
    _voiceBtn.backgroundColor = [UIColor clearColor];
    _voiceBtn.frame = CGRectMake(7,8,34,34);
    [_voiceBtn setImage:[UIImage imageNamed:@"video_voice_nor"] forState:0];
    [_voiceBtn setImage:[UIImage imageNamed:@"video_voice_sel"] forState:UIControlStateSelected];
    [_voiceBtn addTarget:self action:@selector(switchVoice) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_voiceBtn];
    
    _voiceRecodeBtn  = [UIButton buttonWithType:0];
    _voiceRecodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _voiceRecodeBtn.frame = _tv_bg.frame;
    [_voiceRecodeBtn setTitle:YZMsg(@"按住说话") forState:UIControlStateNormal];
    [_voiceRecodeBtn setTitle:YZMsg(@"松开结束") forState:UIControlStateHighlighted];
    _voiceRecodeBtn.layer.masksToBounds = YES;
    _voiceRecodeBtn.layer.cornerRadius = 18;
    _voiceRecodeBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin;
    [_voiceRecodeBtn setBackgroundColor:RGB_COLOR(@"#EA377F", 1)];
    [_voiceRecodeBtn addTarget:self action:@selector(holdDownButtonTouchDown) forControlEvents:UIControlEventTouchDown];
    [_voiceRecodeBtn addTarget:self action:@selector(holdDownButtonTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
    [_voiceRecodeBtn addTarget:self action:@selector(holdDownButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [_voiceRecodeBtn addTarget:self action:@selector(holdDownDragOutside) forControlEvents:UIControlEventTouchDragExit];
    [_voiceRecodeBtn addTarget:self action:@selector(holdDownDragInside) forControlEvents:UIControlEventTouchDragEnter];
    
    [self addSubview:_voiceRecodeBtn];
    _voiceRecodeBtn.hidden = YES;
    
    //表情
    _emojiV = [[twEmojiView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff)];
    _emojiV.delegate = self;
//    [[YBBaseAppDelegate sharedAppDelegate].topViewController.view addSubview:_emojiV];
    [_superView addSubview:_emojiV];
    
    
    //游客加一层遮罩，点击直接跳登陆
    if ([[Config getOwnID] intValue]<0) {
        UIButton *shadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [shadowBtn addTarget:self action:@selector(clickWarningLogin) forControlEvents:UIControlEventTouchUpInside];
        shadowBtn.backgroundColor = UIColor.clearColor;
        [self addSubview:shadowBtn];
        [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.centerX.centerY.equalTo(self);
        }];
    }
    
}
-(void)clickWarningLogin {
    if (self.comToolEvent) {
        self.comToolEvent(@"工具-游客", @{});
    }
}
#pragma mark - 召唤好友
-(void)atFrends {
    [_textField resignFirstResponder];
    _isPrepareEditing = NO;
    [self resetVoiceBtn];
    YBWeakSelf;
    if (!_selV) {
        _selV = [[SelPeopleV alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, _window_height) showType:@"2" selUser:^(NSString *state, MessageListModel *userModel) {
            [weakSelf selCallBack:state uModel:userModel];
        }];
        [_superView addSubview:_selV];
    }
    [UIView animateWithDuration:0.25 animations:^{
        _selV.frame = CGRectMake(0, 0, _window_width, _window_height);
    }];
}
-(void)selCallBack:(NSString *)state uModel:(MessageListModel *)model{
    if ([state isEqual:@"关闭"]) {
        [UIView animateWithDuration:0.25 animations:^{
            _selV.frame = CGRectMake(0, _window_height, _window_width, _window_height);
        } completion:^(BOOL finished) {
            [_selV removeFromSuperview];
            _selV = nil;
        }];
    }else {
        //@
        [UIView animateWithDuration:0.25 animations:^{
            _selV.frame = CGRectMake(0,_window_height, _window_width, _window_height);
        } completion:^(BOOL finished) {
            [_selV removeFromSuperview];
            _selV = nil;
            
            BOOL isRepeat = NO;
            for (NSDictionary *subAtDic in _atArray) {
                NSString *subUid = [NSString stringWithFormat:@"%@",[subAtDic valueForKey:@"uid"]];
                if ([model.uidStr isEqual:subUid]) {
                    //有重复
                    isRepeat = YES;
                }
            }
            //输入框显示用户
            if (isRepeat==NO) {
                _textField.text = [NSString stringWithFormat:@"%@@%@ ",_textField.text,model.unameStr];
                NSDictionary *dic = @{@"name":model.unameStr,@"uid":model.uidStr};
                [_atArray addObject:dic];
            }
            NSLog(@"===输入框显示用户===%@==%@===con:%@",model.uidStr,model.unameStr,_textField.text);
        }];
    }
    [_textField becomeFirstResponder];
    _faceBtn.selected = NO;
    _isPrepareEditing = YES;
}

#pragma mark - 输入框代理事件
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height {
    _textField.height = height;
}

- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView {
    [_textField resignFirstResponder];
    _isPrepareEditing = NO;
    [self pushmessage:nil];
    return YES;
}

- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@""]) {
        NSRange selectRange = growingTextView.selectedRange;
        if (selectRange.length > 0) {
            //用户长按选择文本时不处理
            return YES;
        }
        
        // 判断删除的是一个@中间的字符就整体删除
        NSMutableString *string = [NSMutableString stringWithString:growingTextView.text];
        NSArray *matches = [self findAllAt];
        
        BOOL inAt = NO;
        NSString *delName = @"";
        NSInteger index = range.location;
        for (NSTextCheckingResult *match in matches) {
            NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
            if (NSLocationInRange(range.location, newRange)) {
                //删除的人名称
                delName = [string substringWithRange:newRange];
                inAt = YES;
                index = match.range.location;
                [string replaceCharactersInRange:match.range withString:@""];
                break;
            }
        }
        if (inAt) {
            //删除是输入框中@的人，atArray中也要移除这个人
            NSMutableArray *del_m = [NSMutableArray array];
            for (NSDictionary *subDic in _atArray) {
                if ([delName isEqual:minstr([subDic valueForKey:@"name"])]) {
                    [del_m addObject:subDic];
                }
            }
            [_atArray removeObjectsInArray:del_m];
            
            growingTextView.text = string;
            growingTextView.selectedRange = NSMakeRange(index, 0);
            return NO;
        }
    }
    //判断是回车键就发送出去
    if ([text isEqualToString:@"\n"]) {
        [self pushmessage:nil];
        return NO;
    }
    
    return YES;
}

- (void)growingTextViewDidChange:(HPGrowingTextView *)growingTextView {
    UITextRange *selectedRange = growingTextView.internalTextView.markedTextRange;
    NSString *newText = [growingTextView.internalTextView textInRange:selectedRange];
    
    if (newText.length < 1) {
        // 高亮输入框中的@
        UITextView *textView = _textField.internalTextView;
        NSRange range = textView.selectedRange;
        NSMutableAttributedString *string;

        if(_vcType == 0){
            string= [[NSMutableAttributedString alloc] initWithString:textView.text              attributes:@{NSForegroundColorAttributeName:UIColor.whiteColor,NSFontAttributeName:[UIFont systemFontOfSize:16]}];
        }else{
            string= [[NSMutableAttributedString alloc] initWithString:textView.text              attributes:@{NSForegroundColorAttributeName:RGB_COLOR(@"#969696", 1),NSFontAttributeName:[UIFont systemFontOfSize:16]}];

        }
        
        NSArray *matches = [self findAllAt];
        
        for (NSTextCheckingResult *match in matches) {
            [string addAttribute:NSForegroundColorAttributeName value:AtCol range:NSMakeRange(match.range.location, match.range.length - 1)];
        }
        textView.attributedText = string;
        textView.selectedRange = range;
    }
    if (growingTextView.text.length >0) {
        NSString *theLast = [growingTextView.text substringFromIndex:[growingTextView.text length]-1];
        if ([theLast isEqual:@"@"]) {
            //去掉手动输入的  @
            NSString *end_str = [growingTextView.text substringToIndex:growingTextView.text.length-1];
            _textField.text = end_str;
            [self atFrends];
        }
    }
    
}

- (void)growingTextViewDidChangeSelection:(HPGrowingTextView *)growingTextView {
    // 光标不能点落在@词中间
    NSRange range = growingTextView.selectedRange;
    if (range.length > 0) {
        // 选择文本时可以
        return;
    }
    NSArray *matches = [self findAllAt];
    
    for (NSTextCheckingResult *match in matches) {
        NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
        if (NSLocationInRange(range.location, newRange)) {
            growingTextView.internalTextView.selectedRange = NSMakeRange(match.range.location + match.range.length, 0);
            break;
        }
    }
}

#pragma mark - Private
- (NSArray<NSTextCheckingResult *> *)findAllAt {
    // 找到文本中所有的@
    NSString *string = _textField.text;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kATRegular options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}
-(void)pushmessage:(NSString *)voiceKey{
    
    //发送消息区分：YBLookVideoVC 底部还是 评论view(commentview) 来发送消息
    if (_vcType == 1) {
        if (self.comToolEvent) {
            self.comToolEvent(@"工具-发送消息", @{@"voiceKey":voiceKey?voiceKey:@""});
        }
        [MBProgressHUD hideHUD];
        return;
    }
    
    if ([[Config getOwnID] intValue] <= 0) {
        [_textField resignFirstResponder];
        _isPrepareEditing = NO;
        [PublicObj warnLogin];
        [MBProgressHUD hideHUD];
        return;
    }
    
    /*
     parentid  回复的评论ID
     commentid 回复的评论commentid
     touid     回复的评论UID
     如果只是评论 这三个传0
     */
    if (_textField.text.length == 0 && voiceKey == nil) {
        [MBProgressHUD showError:YZMsg(@"请添加内容后再尝试")];
        [MBProgressHUD hideHUD];
        return;
    }
    NSString *path = _textField.text;
    NSString *at_json = @"";
    //转json、去除空格、回车
    if (_atArray.count>0) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_atArray options:NSJSONWritingPrettyPrinted error:nil];
        at_json = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        at_json = [at_json stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        at_json = [at_json stringByReplacingOccurrencesOfString:@" " withString:@""];
        at_json = [at_json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    /*
    NSString *url = [NSString stringWithFormat:@"Video.setComment&videoid=%@&content=%@&uid=%@&token=%@&touid=%@&commentid=%@&parentid=%@&at_info=%@&type=%@&voice=%@&length=%@",_videoid,voiceKey?@"":path,[Config getOwnID],[Config getOwnToken],_hostid,@"0",@"0",at_json,voiceKey?@"1":@"0",voiceKey,voiceKey?_voiceDution:@"0"];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    */
    NSString *url = @"Video.setComment";
    NSDictionary *postDic = @{@"videoid":_videoid,
                              @"content":voiceKey?@"":path,
                              @"touid":_hostid,
                              @"commentid":@"0",
                              @"parentid":@"0",
                              @"at_info":at_json,
                              @"type":voiceKey?@"1":@"0",
                              @"voice":voiceKey?voiceKey:@"",
                              @"length":voiceKey?_voiceDution:@"0",
    };
    YBWeakSelf;
    [WYNetworking postWithUrl:url Dic:postDic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        
        if(code == 0){
            //更新评论数量
            NSDictionary *infoDic = [info firstObject];
            NSString *newComments = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"comments"]];
            if (weakSelf.comToolEvent) {
                weakSelf.comToolEvent(@"工具-评论", @{@"comments":newComments});
            }
            [MBProgressHUD showPop:msg];
            weakSelf.textField.text = @"";
            [_atArray removeAllObjects];
            weakSelf.textField.placeholder = YZMsg(@"说点什么吧~");
            [_superView endEditing:YES];
            [self hiddenEmojiOrKeyBoard];
            
        }else{
            [MBProgressHUD showPop:msg];
            weakSelf.textField.text = @"";
            [_atArray removeAllObjects];
            weakSelf.textField.placeholder = YZMsg(@"说点什么吧~");
            [_superView endEditing:YES];
            [self hiddenEmojiOrKeyBoard];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}

#pragma mark - 显示表情
-(void)clickFaceBtn {
    [self resetVoiceBtn];
    if (_faceBtn.selected == NO) {
        _faceBtn.selected = YES;
        [_textField resignFirstResponder];
        [UIView animateWithDuration:0.25 animations:^{
            _emojiV.frame = CGRectMake(0, _window_height - (EmojiHeight+ShowDiff), _window_width, EmojiHeight+ShowDiff);
            self.frame = CGRectMake(0, _emojiV.y - 50, _window_width, 50);
        }];
    }else{
        _faceBtn.selected = NO;
        [_textField becomeFirstResponder];
    }
    _isPrepareEditing = YES;

}
#pragma mark - Emoji 代理
-(void)sendimage:(NSString *)str {
    if ([str isEqual:@"msg_del"]) {
        [_textField.internalTextView deleteBackward];
    }else {
        [_textField.internalTextView insertText:str];
    }
}
-(void)clickSendEmojiBtn {
    [self hiddenEmojiOrKeyBoard];
    [self pushmessage:nil];
    
}
-(void)hiddenEmojiOrKeyBoard {
    [_superView endEditing:YES];
    _isPrepareEditing = NO;
    _faceBtn.selected = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, _window_height - 50-ShowDiff, _window_width, 50+ShowDiff);
        _emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
    }];
}
#pragma mark ============录音=============
- (void)switchVoice{
    _voiceBtn.selected  = !_voiceBtn.selected;
    _voiceRecodeBtn.hidden = !_voiceBtn.selected;
    _textField.hidden = _voiceBtn.selected;
    [self hiddenEmojiOrKeyBoard];
}
-(void)resetVoiceBtn {
    [_voiceRecodeBtn setTitle:YZMsg(@"按住说话") forState:UIControlStateNormal];
    [_voiceRecodeBtn setTitle:YZMsg(@"松开结束") forState:UIControlStateHighlighted];
    _voiceBtn.selected = NO;
    _voiceRecodeBtn.hidden = !_voiceBtn.selected;
    _textField.hidden = _voiceBtn.selected;
}
-(void)resetToolState {
    [_textField resignFirstResponder];
    _textField.text = @"";
    _isPrepareEditing = NO;
    [self resetVoiceBtn];
}
- (void)holdDownButtonTouchDown {
    DDLogVerbose(@"Action - didStartRecordingVoice");
    
    //开始录音,记录当前视频播放器的状态
    _playState = self.player.currentPlayerManager.playState;
    
    [self setVideoMuted:YES];
    [self startRecord];
    
}

- (void)holdDownButtonTouchUpOutside {
    DDLogVerbose(@"Action - didCancelRecordingVoice");
    [self setVideoMuted:NO];
    [self cancelRecord];

}

- (void)holdDownButtonTouchUpInside {
    DDLogVerbose(@"Action - didFinishRecordingVoiceAction");
    [self setVideoMuted:NO];
    [self finishRecorded];

}

- (void)holdDownDragOutside {
    DDLogVerbose(@"Action - didDragOutsideAction");
    [self resumeRecord];

}

- (void)holdDownDragInside {
    DDLogVerbose(@"Action - didDragInsideAction");
    [self pauseRecord];

}
- (void)pauseRecord {
    [self.voiceRecordHUD pauseRecord];
}

- (void)resumeRecord {
    [self.voiceRecordHUD resaueRecord];
}

- (void)cancelRecord {
    YBWeakSelf;
    [self.voiceRecordHUD cancelRecordCompled:^(BOOL fnished) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.voiceRecordHUD = nil;
    }];
    [self.voiceRecordHelper cancelledDeleteWithCompletion:^{
        
    }];
}
#pragma mark - Voice Recording Helper Method
- (void)startRecord {
    DDLogDebug(@"Action - startRecord");
    [self.voiceRecordHUD startRecordingHUDAtView:_superView];
    [self.voiceRecordHelper startRecordingWithPath:[self getRecorderPath] andVideo:YES  StartRecorderCompletion:^{
    }];
}

- (XHVoiceRecordHelper *)voiceRecordHelper {
    if (!_voiceRecordHelper) {
        YBWeakSelf;
        _voiceRecordHelper = [[XHVoiceRecordHelper alloc] init];
        
        _voiceRecordHelper.maxTimeStopRecorderCompletion = ^{
            DDLogDebug(@"已经达到最大限制时间了，进入下一步的提示");
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf finishRecorded];
        };
        
        _voiceRecordHelper.peakPowerForChannel = ^(float peakPowerForChannel) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            strongSelf.voiceRecordHUD.peakPower = peakPowerForChannel;
        };
        
        _voiceRecordHelper.maxRecordTime = 60;
    }
    return _voiceRecordHelper;
}

- (XHVoiceRecordHUD *)voiceRecordHUD {
    if (!_voiceRecordHUD) {
        _voiceRecordHUD = [[XHVoiceRecordHUD alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
    }
    return _voiceRecordHUD;
}
- (void)finishRecorded {
    DDLogDebug(@"Action - finishRecorded");
    YBWeakSelf;
    [self.voiceRecordHUD stopRecordCompled:^(BOOL fnished) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.voiceRecordHUD = nil;
    }];
    [self.voiceRecordHelper stopRecordingWithStopRecorderCompletion:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf SendMessageWithVoice:strongSelf.voiceRecordHelper.recordPath
                           voiceDuration:strongSelf.voiceRecordHelper.recordDuration];
    }];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}

#pragma mark - Message Send helper Method
#pragma mark --发送语音
- (void)SendMessageWithVoice:(NSString *)voicePath
               voiceDuration:(NSString*)voiceDuration {
    DDLogDebug(@"Action - SendMessageWithVoice");
    if (voicePath == voicePathhh) {
        return;
    }
    if ([voiceDuration integerValue]<0.5 || [voiceDuration integerValue]>60) {
        if ([voiceDuration integerValue]<0.5) {
            DDLogDebug(@"录音时长小于 0.5s");
            [MBProgressHUD showError:YZMsg(@"录音时间过短")];
        } else {
            DDLogDebug(@"录音时长大于 60s");
            [MBProgressHUD showError:YZMsg(@"录音时长大于 60s")];
        }
        return;
    }
    voicePathhh = voicePath;
    _voiceDution = voiceDuration;
    [self clickPublishBtn];
}
#pragma mark - RecorderPath Helper Method
- (NSString *)getRecorderPath {
    NSString *recorderPath = nil;
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yy-MMMM-dd";
    recorderPath = [[NSString alloc] initWithFormat:@"%@/Documents/", NSHomeDirectory()];
    dateFormatter.dateFormat = @"yyyy-MM-dd-hh-mm-ss";
    recorderPath = [recorderPath stringByAppendingFormat:@"%@-voiceComment.wav", [dateFormatter stringFromDate:now]];
    return recorderPath;
}
- (void)setVideoMuted:(BOOL)isMuted{

    if (self.comToolEvent) {
        self.comToolEvent(@"工具-录音", @{@"mutedType":@(isMuted),@"playState":@(_playState)});
    }
}

#pragma mark - 发布
- (void)clickPublishBtn {
    [_superView endEditing:YES];
    _isPrepareEditing = NO;
    
    YBWeakSelf;
    [[YBStorageObj storageManeger]getCOSType:^(int code) {
        if (code == 0) {
            [weakSelf startUpload];
        }
    }];

}

-(void)startUpload {
    NSString *filePath = voicePathhh;
    //传视频
    NSString *voiceoName = [PublicObj getNameBaseCurrentTime:@".wav"];
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [[YBStorageObj storageManeger]yb_storageVideoOrVoice:filePath andName:voiceoName progress:^(CGFloat percent) {
        
    }complete:^(int code, NSString *key) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        if (code == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf pushmessage:key];
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showPop:YZMsg(@"添加失败")];
            });
        }
    }];
}

-(void)networkState{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:YZMsg(@"上传失败")];
                break;
            default:
                break;
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring]; //开启网络监控
}


@end
